package com.study.dao;

import com.study.domain.User;
import com.study.util.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDao {

    private QueryRunner queryRunner = new QueryRunner();


    public User login(String name, String password) {
        User user = null;
        try {
            user = queryRunner.query(DbUtils.getConnection(), "select * from user where name ='" + name + "' and password = '" + password + "'", new BeanHandler<>(User.class));
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return user;
    }

    public User selectByName(String name) {
        User user = null;
        try {
            user = queryRunner.query(DbUtils.getConnection(), "select * from user where name ='" + name + "' ", new BeanHandler<>(User.class));
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return user;
    }

    public void register(String name, String password) {
        try {
            queryRunner.update(DbUtils.getConnection(), "insert into user(name,password,addtime) values('" + name + "','" + password + "',now())");
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public List<User> list() {
        List<User> list = null;
        try {
            list = queryRunner.query(DbUtils.getConnection(), "select * from user ", new BeanListHandler<>(User.class));
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return list;
    }

    public void del(Integer userId) {
        try {
            queryRunner.update(DbUtils.getConnection(), "delete from  user where id = " + userId);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
